package sip

import (
	"encoding/xml"
	"fmt"
	"strconv"
	"math/rand"
	"time"

	"gitee.com/larry_wan/go-lib/etree"
)

type Channel struct {
	DeviceID      string
	Name          string
	Manufacturer  string
	Model         string
	Owner         string
	CivilCode     string
	Block         string
	Address       string
	Parental      string
	ParentID      string
	SafetyWay     int
	RegisterWay   string
	CertNum       string
	Certifiable   int
	ErrorCode     int
	EndTime       string
	Secrecy       int
	IPAddress     string
	Port          int
	Password      string
	Status        string
	Longitude     float64
	Latitude      float64
	PTZType       int
	DownloadSpeed string
	Record        uint

	// 扩展
	Var           string
	Type          string
}

func (ch *Channel) String() string {
	return fmt.Sprintf("Channel[%s] Name[%s]", ch.DeviceID, ch.Name)
}

func (ch *Channel) SSRC(prefix string) string {
	if len(ch.DeviceID) <= 8 {
		return prefix
	}
	// if len(ch.DeviceID) < 20 {
	// 	return prefix + ch.DeviceID[3:8] + ch.DeviceID[11:18]
	// }
	// return prefix + ch.DeviceID[3:8] + ch.DeviceID[13:20]
	if len(ch.DeviceID) < 20 {
		return prefix + ch.DeviceID[3:6] + ch.DeviceID[12:18]
	}
	return prefix + ch.DeviceID[3:6] + ch.DeviceID[14:20]
}

func (ch *Channel) JPGID() string {
	rand.Seed(time.Now().Unix())
	return ch.DeviceID[15:20] + fmt.Sprintf("%d", rand.Int31())
}

func UnmarshalChannel(e *etree.Element) (ch *Channel, err error) {
	if e == nil {
		err = fmt.Errorf("xml not found")
		return
	}
	doc := etree.NewDocument()
	doc.SetRoot(e)
	doc.Indent(4)
	xmlStr, err := doc.WriteToString()
	if err != nil {
		return
	}
	_ch := &Channel{}
	err = xml.Unmarshal([]byte(xmlStr), _ch)
	if err != nil {
		return
	}
	if el := e.FindElementPath(etree.MustCompilePath("Info/PTZType")); el != nil {
		_ch.PTZType, _ = strconv.Atoi(el.Text())
	}
	if el := e.FindElementPath(etree.MustCompilePath("Info/DownloadSpeed")); el != nil {
		_ch.DownloadSpeed = el.Text()
	}
	ch = _ch
	return
}
